/* eslint-disable react/self-closing-comp */
/* eslint-disable no-nested-ternary */
/* eslint-disable react/no-multi-comp */
import React, { Component, cloneElement, createElement } from "react";
import { Checkbox, DatePicker, Info, Input, Radio } from "antd";
import FileUpload from "components/file-upload";
import UnifiedTable from "components/template/widget/unified-table/UnifiedTable";

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;

const formFieldOfProvider = [
  {
    key: "name",
    columnName: "name",
    columnComment: "姓名",
    widgetType: 0,
    visible: 1,
  },
  {
    key: "company",
    columnName: "company",
    columnComment: "公司",
    widgetType: 0,
    visible: 1,
  },
  {
    key: "deparment",
    columnName: "deparment",
    columnComment: "部门",
    widgetType: 0,
    visible: 1,
  },
  {
    key: "position",
    columnName: "position",
    columnComment: "职务",
    widgetType: 0,
    visible: 1,
  },
];

const formFieldOfCustomer = [
  {
    key: "name",
    columnName: "name",
    columnComment: "姓名",
    widgetType: 0,
    visible: 1,
  },
];

/**
 * @param {{
 *  note?: string
 * }} props
 */
const UnifiedLabel = (props) => {
  const { children, style = {}, note = "", checked, noteStar, ...otherProps } = props;

  const labelStyle = {};

  const noteStyle = {};

  const WrapperComponent = "span";

  return createElement(
    WrapperComponent,
    { ...otherProps, style },
    <span>
      <span>{children}</span>
      {note && checked && (
        <span
        >
          （{noteStar ? <span style={{color: "#FF6680" }}>*</span> : ''}<span>{note}</span>)
        </span>
      )}
    </span>
  );
};

class UnifiedSelectTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value === "[]" || !props.value ? "[{}]" : props.value,
    };
  }

  onChange = (value) => {
    this.setState({ value });
    if (this.props.onChange) {
      this.props.onChange(value);
    }
  };

  render() {
    const { formField } = this.props;
    const { value } = this.state;
    return (
      <div>
        <UnifiedTable
          showIndex
          exportFile={false}
          importFile={false}
          cellMinWidth={100}
          formField={JSON.stringify(formField)}
          value={value}
          onChange={this.onChange}
        ></UnifiedTable>
      </div>
    );
  }
}

class UnifiedAttachment extends Component {
  constructor(props) {
    super(props);
    const propsValue = props.value || {};
    this.state = {
      fileList: propsValue.fileList || [],
      message: propsValue.message || "",
    };
  }

  onInputChange = (e) => {
    this.setState({ message: e.target.value }, this.emitChange);
  };
  onFileChange = (fileList) => {
    this.setState({ fileList }, this.emitChange);
  };

  emitChange = () => {
    if (this.props.onChange) {
      this.props.onChange({
        message: this.state.message,
        fileList: this.state.fileList,
      });
    }
  };

  render() {
    const { showUpload = true, placeholder = "请具体说明" } = this.props;
    const { fileList, message } = this.state;

    return (
      <div>
        <Input
          placeholder={placeholder}
          value={message}
          onChange={this.onInputChange}
        ></Input>
        <div style={{ paddingTop: 10 }}>
          {showUpload && (
            <div
              style={{
                borderStyle: "dashed",
                borderColor: "#C7C7C7",
                borderWidth: 0,
                borderBottomWidth: 1,
              }}
            >
              <FileUpload
                defaultFileList={this.state.fileList}
                attachmentType="OTHER"
                showFileName
                isShowDefault
                onChange={this.onFileChange}
              />
              {/* {this.state.fileList.length>0?null:<p style={{color:'#FF6680'}}>请上传附件！</p>} */}
            </div>
          )}
        </div>
      </div>
    );
  }
}

class UnifiedSelectType extends Component {
  /**
   *
   * @param {{options: UnifiedSelectOption, type: 'checkbox' | 'radio' }} props
   */
  constructor(props) {
    super(props);
    this.updateValue(props);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.value !== this.props.value) {
      this.updateValue(this.props);
    }
  }

  onSlotChangeWrapper = (option) => {
    const onSlotChange = (e) => {
      let value = e;
      if (option.slotType === "input") {
        value = e.target.value;
      }
      this.setState(
        {
          slots: {
            ...this.state.slots,
            [option.key]: value,
          },
        },
        this.emitChange
      );
    };

    return onSlotChange;
  };

  onGroupChange = (e) => {
    const { type = "checkbox", options } = this.props;
    let selected = type === "checkbox" ? e : [e.target.value];
    console.log('e=================', e)
    let arr = [];
    selected.map(item => {
      if (item) {
        arr.push(item)
      }
    })
    this.setState({ selected: arr }, this.emitChange);
  };

  getSlotValue = (option) => {
    return this.state.slots[option.key];
  };

  updateValue = (props) => {
    const slots = {};
    const value = props.value || [];
    value.forEach((option) => {
      slots[option.key] = option.slot;
    });
    this.state = {
      value,
      // selected: value.length === 6?value.map((item) => item.checked):value.map((item) => item.key),
      selected: value.map((item) => item.checked),
      slots,
    };
  };

  emitChange = () => {
    const { onChange, options } = this.props;
    const { slots } = this.state;
    let selected = this.state.selected;
    if (selected && selected.length === 6) {
      selected = ['option1', 'option2', 'option3', 'option4', 'option5', 'option6']
    }
    console.log("emitChange", selected)
    if (onChange) {
      const value = options
        .filter((item) => {
          return selected.indexOf(item.key) > -1;
        })
        .map((item) => {
          return {
            ...item,
            slot: this.state.slots[item.key],
          };
        });
      console.log('value=======', value)
      onChange(value);
    }
  };

  render() {
    const { value, type = "checkbox", options = [] } = this.props;
    let selected = this.state.selected;
    if (selected && selected.length === 6 && !selected[0] && !selected[1]) {
      selected = ['option1', 'option2', 'option3', 'option4', 'option5', 'option6']
    }
    const Widget = type === "checkbox" ? CheckboxGroup : RadioGroup;
    const ItemWidget = type === "checkbox" ? Checkbox : Radio;
    const groupValue = type === "checkbox" ? selected : selected[0];
    console.log("selected=======", selected)
    return (
      <Widget
        onChange={this.onGroupChange}
        value={groupValue}
        style={{ width: "100%" }}
      >
        {options.map((option) => {
          const checked = !!selected.find((item) => item === option.key);

          let slot = <Input placeholder={option.isPlaceHolder ? '请输入' : '请具体说明'}></Input>;

          if (option.slotType) {
            if (option.slotType === "attachment") {
              slot = <UnifiedAttachment></UnifiedAttachment>;
            } else if (option.slotType === "tableOfPrivider") {
              slot = <UnifiedSelectTable formField={formFieldOfProvider} />;
            } else if (option.slotType === "tableOfCustomer") {
              slot = <UnifiedSelectTable formField={formFieldOfCustomer} />;
            }
          }

          return (
            <div key={option.key} data-checked={checked}>
              <div>
                <ItemWidget
                  // checked={checked}
                  value={option.key}
                  style={{ width: "100%" }}
                >
                  <UnifiedLabel note={option.note} checked={checked} noteStar={option.noteStar}>{option.title}</UnifiedLabel>
                </ItemWidget>
                {checked && option.slotType && (
                  <div
                    style={{
                      paddingTop: 10,
                      paddingBottom: 10,
                      paddingLeft: 24,
                    }}
                  >
                    {cloneElement(slot, {
                      onChange: this.onSlotChangeWrapper(option),
                      value: this.getSlotValue(option),
                    })}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </Widget>
    );
  }
}

UnifiedSelectType.propTypes = {
  /**
   * @typedef {(
   *  {
   *    title: string
   *    note?: string
   *    slotType?: 'tableOfPrivider' | 'tableOfCustomer' | 'input' | 'attachment'
   *  }[]
   * )} UnifiedSelectOption
   *
   * 目前只支持上面4种slotType, 以后可以扩展
   *
   * @type UnifiedSelectOption
   */

  options: React.PropTypes.any,
  /**
   * @typedef  {('radio' | 'checkbox')} UnifiedSelectType
   * @type UnifiedSelectType
   */
  type: React.PropTypes.any,
};

export default UnifiedSelectType;

export { formFieldOfProvider, formFieldOfCustomer };
